<template>
  <div class>
    <div class="card tr mb2">
      <el-tooltip content="显示字段筛选" placement="bottom" effect="light">
        <el-popover placement="bottom" width="200" trigger="click">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选
          </el-checkbox>
          <el-checkbox-group v-model="showItemList" @change="handleCheckedChange">
            <el-checkbox v-for="(item,key) in allItemList" :key="key" :label="item">{{item.name}}</el-checkbox>
          </el-checkbox-group>
          <el-button slot="reference" icon="el-icon-menu" size="mini" type="primary" circle></el-button>
        </el-popover>
      </el-tooltip>
      <el-tooltip content="展开/收起表单" placement="bottom" effect="light">
        <el-button icon="el-icon-search" @click="formShow= !formShow" size="mini" type="primary" circle></el-button>
      </el-tooltip>
      <el-tooltip content="下载当前表格数据" placement="bottom" effect="light">
        <el-button icon="el-icon-download" @click="handleDownload" size="mini" type="primary" circle></el-button>
      </el-tooltip>
      <el-button size="mini" type="primary" icon="el-icon-plus" @click="showDialog">添加</el-button>
    </div>
    <div class="card" v-show="formShow">
      <el-form size="mini" :style="style" :model="ruleForm" ref="ruleForm" inline label-width="100px"
        class="demo-ruleForm">
        <my-form-item label="组件名称" prop="componentName">
          <el-input size="mini" v-model="ruleForm.componentName"></el-input>
        </my-form-item>
        <my-form-item label="组件标题" prop="componentTitle">
          <el-input size="mini" v-model="ruleForm.componentTitle"></el-input>
        </my-form-item>
        <my-form-item label="应用路径" prop="applicationPath">
          <el-input size="mini" v-model="ruleForm.applicationPath"></el-input>
        </my-form-item>
        <my-form-item>
          <el-button size="mini" type="primary" @click="submitForm('ruleForm')">查询</el-button>
          <el-button size="mini" @click="resetForm('ruleForm')">重置</el-button>
        </my-form-item>
      </el-form>
    </div>
    <el-table stripe :data="tableData" border style="width: 100%">
      <el-table-column type="index" width="60px" align="center" fixed="left" label="序号"></el-table-column>
      <el-table-column label="组件标题"  prop="componentTitle" align="center" min-width="120"/>
      <el-table-column label="组件名称"  prop="componentName" align="center" min-width="220"/>
      <el-table-column v-for="(item,index) in showItemList" align="center" :width="item.width || '' " :key="index"
        :label="item.name">
        <template slot-scope="scope">
            <template v-if="!item.formatter">
            <el-tooltip effect="light" :content="scope.row[item.key]" :visible-arrow="false" placement="bottom">
                <span> {{ scope.row[item.key] }}</span>
            </el-tooltip>
            </template>
          <template v-else>
              <el-tooltip effect="light" :content="item.formatter(scope.row, item)" :visible-arrow="false" placement="bottom">
            <span v-text="item.formatter(scope.row, item)"></span>
          </el-tooltip>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180px" fixed="right" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="showEditDialog(scope.$index, scope.row)">编辑</el-button>
          <el-button :disabled="scope.row.componentType!='2'" size="mini" @click="configForm(scope.$index, scope.row)">配置表单</el-button>
          <!-- <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <el-card style="text-align:right;">
      <el-pagination @size-change="sizeChange" @current-change="currentChange" :current-page="currentPage"
        :page-sizes="[ 10, 20,30, 40]" :page-size="pageSize" background layout="total, sizes, prev, pager, next"
        :total="total"></el-pagination>
    </el-card>
    <!-- --------------------------------------------------------添加弹出框 -->
    <el-dialog title="新增管理" append-to-body :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form size="mini" :style="style" :model="addForm" ref="addForm" :rules="rules" inline label-width="100px"
        class="demo-ruleForm">
        <my-form-item label="组件标题" :label-width="formLabelWidth" prop="componentTitle">
          <el-input size="mini" maxlength="255" style="width:360px !important;" v-model="addForm.componentTitle">
          </el-input>
        </my-form-item>
        <my-form-item label="组件名称" :label-width="formLabelWidth" prop="componentName">
          <el-input size="mini" maxlength="255" style="width:360px !important;" v-model="addForm.componentName">
          </el-input>
        </my-form-item>
        <my-form-item label="组件路径" :label-width="formLabelWidth" prop="componentPath">
          <el-input size="mini" maxlength="255" style="width:360px !important;" v-model="addForm.componentPath">
          </el-input>
        </my-form-item>
        <my-form-item label="组件类型" :label-width="formLabelWidth" prop="componentType">
          <!-- <el-input size="mini" maxlength="255" style="width:360px !important;" v-model="addForm.componentType"></el-input> -->
          <el-switch size="mini" v-model="addForm.componentType" active-text="基本组件" inactive-text="动态组件"
            active-value="1" inactive-value="2">
          </el-switch>
        </my-form-item>
        <my-form-item label="组件状态" :label-width="formLabelWidth" prop="componentStatus">
          <el-switch size="mini" v-model="addForm.componentStatus" active-text="启用" inactive-text="禁用" active-value="1"
            inactive-value="0">
          </el-switch>
        </my-form-item>
        <my-form-item label="应用路径" :label-width="formLabelWidth" prop="applicationPath">
          <el-input size="mini" maxlength="255" disabled style="width:360px !important;"
            v-model="addForm.applicationPath"></el-input>
        </my-form-item>
        <my-form-item label="顺序" :label-width="formLabelWidth" prop="applicationOrder">
          <el-input size="mini" maxlength="255" style="width:360px !important;" v-model="addForm.applicationOrder">
          </el-input>
        </my-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogFormVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="handleAdd()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- --------------------------------------------------------编辑弹出框 -->
    <el-dialog title="编辑管理" append-to-body :visible.sync="dialogEditVisible" :close-on-click-modal="false">
      <el-form size="mini" :style="style" :model="editForm" ref="editForm" :rules="rules" inline label-width="100px"
        class="demo-ruleForm">
        <my-form-item label="组件标题" :label-width="formLabelWidth" prop="componentTitle">
          <el-input size="mini" maxlength="255" style="width:360px !important;" v-model="editForm.componentTitle">
          </el-input>
        </my-form-item>
        <my-form-item label="组件名称" :label-width="formLabelWidth" prop="componentName">
          <el-input size="mini" maxlength="255" style="width:360px !important;" v-model="editForm.componentName">
          </el-input>
        </my-form-item>
        <my-form-item label="组件路径" :label-width="formLabelWidth" prop="componentPath">
          <el-input size="mini" maxlength="255" style="width:360px !important;" v-model="editForm.componentPath">
          </el-input>
        </my-form-item>
        <my-form-item label="组件类型" :label-width="formLabelWidth" prop="componentType">
          <el-switch size="mini" v-model="editForm.componentType" active-text="基本组件" inactive-text="动态组件"
            active-value="1" inactive-value="2">
          </el-switch>
        </my-form-item>
        <my-form-item label="组件状态" :label-width="formLabelWidth" prop="componentStatus">
          <el-switch size="mini" v-model="editForm.componentStatus" active-text="启用" inactive-text="禁用" active-value="1"
            inactive-value="0">
          </el-switch>
        </my-form-item>
        <my-form-item label="应用路径" :label-width="formLabelWidth" prop="applicationPath">
          <el-input size="mini" maxlength="255" disabled style="width:360px !important;"
            v-model="editForm.applicationPath"></el-input>
        </my-form-item>
        <my-form-item label="顺序" :label-width="formLabelWidth" prop="applicationOrder">
          <el-input size="mini" maxlength="255" disabled style="width:360px !important;" v-model="editForm.applicationOrder">
          </el-input>
        </my-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogEditVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="handleEdit()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="表单配置" width="75%" append-to-body :visible.sync="dialogConfigFormVisible"
      :close-on-click-modal="false">
      <configForm ref="configForm"></configForm>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogConfigFormVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="saveConfigForm()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  const defaultFormThead = [
    { key: "componentType", name: "组件类型", width: "80px", 
      formatter(row,item){
        if(row.componentType=='1'){
          return '基本组件';
        }else{
          return '动态组件';
        }
      }
    },
    { key: "componentStatus", name: "组件状态", width: "80px",
      formatter(row,item){
          if(row.componentStatus=='1'){
            return '启用';
          }else{
            return '禁用';
          }
        }
    },
    { key: "componentPath", name: "组件路径", width: "220px" },
    { key: "applicationPath", name: "应用路径", width: "220px" },
    { key: "applicationOrder", name: "顺序", width: "80px" },
    { key: "createUserName", name: "创建人", width: "120px" },
    { key: "createTime", name: "创建时间", width: "220px" },
  ];
  import configForm from '@/pages/component/configForm.vue'
  export default {
    components: { configForm },
    data() {
      return {
        registerId: '',
        dialogConfigFormVisible: false,
        checkAll: true,
        isIndeterminate: false,
        allItemList: defaultFormThead,
        showItemList: defaultFormThead,
        formShow: false,
        dialogFormVisible: false,
        dialogEditVisible: false,
        offForm: true, //是否折叠
        folding: false, //表单是否超过一行
        formLabelWidth: "180px",
        tableData: [],
        total: 0,
        pageSize: 10,
        currentPage: 1,
        ruleForm: {
          componentName: '',
          componentTitle: '',
          applicationPath: '',
        },
        style: {},
        rules: {
          componentName: [{ required: true, message: "请输入组件名称", trigger: "change" }],
          componentPath: [{ required: true, message: "请输入组件路径", trigger: "change" }],
          applicationPath: [{ required: true, message: "请输入应用路径", trigger: "change" }],
          applicationOrder: [{ required: true, message: "请输入顺序", trigger: "change" }],
          componentTitle: [{ required: true, message: "请输入组件标题", trigger: "change" }],
        },
        addForm: {
          componentName: '',
          componentPath: '',
          applicationPath: '',
          applicationOrder: '',
          componentTitle: '',
          componentStatus: '1',
          componentType: '1',
        },
        editForm: {
          componentName: '',
          componentPath: '',
          applicationPath: '',
          applicationOrder: '',
          componentTitle: '',
          componentStatus: '',
          componentType: '',
        }
      };
    },

    mounted() {
      // this.init();
      let formHeight = this.$refs.ruleForm.$el.clientHeight;
      if (formHeight > 62) {
        this.folding = true;
        this.style = {
          height: "62px",
          overflow: "hidden"
        };
      } else {
        this.folding = false;
        this.style = {
          height: "auto",
          overflow: "hidden"
        };
      }
    },
    computed: {
    },
    watch: {
      offForm: function (v) {
        if (v) {
          this.style = {
            height: "62px",
            overflow: "hidden"
          };
        } else {
          this.style = {
            height: "auto",
            overflow: "hidden"
          };
        }
      }
    },
    methods: {
      saveConfigForm() {
        let componentPropertiesList = this.$refs.configForm.getData();
        let params = {
          componentPropertiesList: componentPropertiesList,
          registerId: this.registerId,
        }
        this.$api
          .post("/api/biz/components/componentProperties/doSaveOrUpdateBatch", params)
          .then(res => {
            if (res.retHead.code == "0000000") {
              this.$message({
                message: "保存成功！",
                type: "success"
              });
              this.dialogConfigFormVisible = false;
            } else {
              this.$message({
                message: res.retHead.message,
                type: "error"
              });
            }
          });
      },
      configForm(index, row) {
        this.registerId = '',
          this.dialogConfigFormVisible = true;
        this.registerId = row.id;
        this.$nextTick(c => {
          this.$refs.configForm.initData(row.id);
        });
      },
      handleDownload() {
        this.downloadLoading = true;
        import("@/vendor/Export2Excel").then(excel => {
          const tHeader = [
            "注册组件ID",
            "组件名称",
            "组件路径",
            "应用路径",
            "顺序",
            "创建人id",
            "创建人",
            "创建时间",
            "组件标题",
          ];
          const filterVal = [
            "id",
            "componentName",
            "componentPath",
            "applicationPath",
            "applicationOrder",
            "createUserId",
            "createUserName",
            "createTime",
            "componentTitle",
          ];
          const data = this.formatJson(filterVal, this.tableData);
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: "table-list"
          });
          this.downloadLoading = false;
        });
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v =>
          filterVal.map(j => {
            if (j === "timestamp") {
              return parseTime(v[j]);
            } else {
              return v[j];
            }
          })
        );
      },
      handleCheckedChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === defaultFormThead.length;
        this.isIndeterminate =
          checkedCount > 0 && checkedCount < defaultFormThead.length;
      },
      handleCheckAllChange(val) {
        this.showItemList = val ? defaultFormThead : [];
        this.isIndeterminate = false;
      },
      sizeChange(n) {
        this.pageSize = n;
        this.init();
      },
      currentChange(n) {
        this.currentPage = n;
        this.init();
      },
      dataInit(applicationPath) {
        this.addForm.applicationPath = applicationPath;
        this.ruleForm.applicationPath = applicationPath;
        this.init();
      },
      init() {
        let searchForm = {};
        searchForm.componentName = this.ruleForm.componentName;
        searchForm.componentTitle = this.ruleForm.componentTitle;
        searchForm.applicationPath = this.ruleForm.applicationPath;
        let params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          ...searchForm
        };
        this.$api
          .formPost("/api/biz/components/componentRegister/doGetList", params)
          .then(res => {
            if (res.retHead.code == "0000000") {
              this.tableData = res.retBody.list;
              this.total = res.retBody.total;
              this.currentPage = res.retBody.pageNum;
            }
          });
      },
      showDialog() {
        this.dialogFormVisible = true;
        this.$nextTick(() => {
          this.resetForm("addForm");
        });
        this.form = {};
      },
      showEditDialog(index, row) {
        if (row.id) {
          this.editForm.id = row.id;
        } else {
          this.editForm.id = '';
        }
        if (row.componentName) {
          this.editForm.componentName = row.componentName;
        } else {
          this.editForm.componentName = '';
        }
        if (row.componentPath) {
          this.editForm.componentPath = row.componentPath;
        } else {
          this.editForm.componentPath = '';
        }
        if (row.componentType) {
          this.editForm.componentType = row.componentType;
        } else {
          this.editForm.componentType = '';
        }
        if (row.componentStatus) {
          this.editForm.componentStatus = row.componentStatus;
        } else {
          this.editForm.componentStatus = '';
        }
        if (row.applicationPath) {
          this.editForm.applicationPath = row.applicationPath;
        } else {
          this.editForm.applicationPath = '';
        }
        if (row.applicationOrder) {
          this.editForm.applicationOrder = row.applicationOrder;
        } else {
          this.editForm.applicationOrder = '';
        }
        if (row.createUserId) {
          this.editForm.createUserId = row.createUserId;
        } else {
          this.editForm.createUserId = '';
        }
        if (row.createUserName) {
          this.editForm.createUserName = row.createUserName;
        } else {
          this.editForm.createUserName = '';
        }
        if (row.createTime) {
          this.editForm.createTime = row.createTime;
        } else {
          this.editForm.createTime = '';
        }
        if (row.componentTitle) {
          this.editForm.componentTitle = row.componentTitle;
        } else {
          this.editForm.componentTitle = '';
        }
        this.dialogEditVisible = true;
      },
      handleAdd() {
        this.$refs.addForm.validate(valid => {
          if (valid) {
            let user = JSON.parse(sessionStorage.getItem("user"));
            let addFormParams = {};
            addFormParams.createUserId = user.id;
            addFormParams.createUserName = user.realName;
            addFormParams.componentName = this.addForm.componentName;
            addFormParams.componentPath = this.addForm.componentPath;
            addFormParams.applicationPath = this.addForm.applicationPath;
            addFormParams.applicationOrder = this.addForm.applicationOrder;
            addFormParams.componentTitle = this.addForm.componentTitle;
            addFormParams.componentType = this.addForm.componentType;
            addFormParams.componentStatus = this.addForm.componentStatus;
            this.$api
              .formPost("/api/biz/components/componentRegister/doSave", addFormParams)
              .then(res => {
                if (res.retHead.code == "0000000") {
                  this.$message({
                    message: "添加成功！",
                    type: "success"
                  });
                  this.dialogFormVisible = false;
                  this.init();
                } else {
                  this.$message({
                    message: "添加失败！",
                    type: "error"
                  });
                }
              });
          } else {
            this.$message.error("请完善表单！")
          };
        });
      },
      handleEdit() {
        this.$refs.editForm.validate(valid => {
          if (valid) {
            let editFormParams = {};
            editFormParams.id = this.editForm.id;
            editFormParams.componentName = this.editForm.componentName;
            editFormParams.componentPath = this.editForm.componentPath;
            editFormParams.applicationPath = this.editForm.applicationPath;
            editFormParams.applicationOrder = this.editForm.applicationOrder;
            editFormParams.componentTitle = this.editForm.componentTitle;
            editFormParams.componentType = this.editForm.componentType;
            editFormParams.componentStatus = this.editForm.componentStatus;
            this.$api
              .formPost("/api/biz/components/componentRegister/doModById", editFormParams)
              .then(res => {
                if (res.retHead.code == "0000000") {
                  this.$message.success("执行成功！");
                  this.init();
                  this.dialogEditVisible = false;
                } else {
                  this.$message.error("执行失败！");
                }
              });
          } else {
            this.$message.error("请完善表单！")
          };
        });
      },

      handleDelete(index, row) {
        this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.$api
              .formPost("/api/biz/components/componentRegister/doRmById", {
                id: row.id
              })
              .then(res => {
                if (res.retHead.code == "0000000") {
                  this.$message({
                    message: "操作成功！",
                    type: "success"
                  });
                  this.init();
                } else {
                  this.$message({
                    message: "操作失败！",
                    type: "error"
                  });
                }
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      },
      submitForm(formName) {
        this.init();
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    },
    created() { }
  };
</script>
<style lang='scss' scoped>
  .btns {
    text-align: right;
  }

  .icon-arrow {
    position: absolute;
    bottom: 5px;
    left: 0;
    width: 100%;
    height: 1px;
    background-color: #f1f1f1;

    i {
      background-color: #fff;
      position: absolute;
      color: #999;
      bottom: -7px;
      margin-left: 50%;
      transform: translateX(-50%);
      cursor: pointer;
    }
  }
</style>